import { warn } from "./functions";

/**
 * @param {function} getter 获取要等的对象，如果返回 undefined（不含 null）就会继续等待
 * @param {*} timeoutSeconds 等待超时时间，以秒为单位
 * @param {*} interval 检查频率，默认是 200 毫秒检查一次
 * @returns
 */
export async function waitObject(getter, timeoutSeconds = 0, interval = 200) {
    const timeout = (timeoutSeconds || 0) * 1000;
    return new Promise((resolve, reject) => {
        const startTime = Date.now();
        let errorCount = 0;

        const timer = setInterval(async () => {
            const result = await (
                async () => getter()
            )().catch(() => (errorCount++, undefined));

            if (result ?? null !== null) {
                clearInterval(timer);
                resolve(result);
                return;
            }

            if (errorCount > 100) {
                clearInterval(timer);
                reject({ type: "too more error" });
            }
            else if (timeout && Date.now() - startTime > timeout) {
                clearInterval(timer);
                reject({ type: "timeout", seconds: timeoutSeconds });
            }
        }, interval);
    });
}

export function warnWaitError(message) {
    return err => {
        warn(`[${err.type}]`, message);
        warn(err);
    };
}
